package punctuatedEquilibrium;

import java.util.LinkedList;
import java.util.List;

public class SetOfPhenotypes {

	private List<Phenotype>	collection;
	private Double[]		traitValues;
	private Double[]		sumOfTraitValues;
	private Double[]		averageTraitValues;
	private Trait[]			averageTraits;
	private int				numberOfTraits;

	public SetOfPhenotypes() {
		collection = new LinkedList<Phenotype>();
	}

	public void add(Phenotype phenotypeToAddToCollection) {
		collection.add(phenotypeToAddToCollection);
	}

	public Phenotype computeAveragePhenotype() {
		if (!collection.isEmpty()) {
			return averageOverCollection();
		} else {
			return PhenotypeFactory.getNullPhenotype();
		}
	}

	private Phenotype averageOverCollection() {
		numberOfTraits = collection.get(0).getArrayOfVariables().length;
		averageTraitValues = new Double[numberOfTraits];
		sumOfTraitValues = new Double[numberOfTraits];
		for (int i = 0; i < numberOfTraits; i++) {
			sumOfTraitValues[i] = 0D;
		}
		computeSumOfTraitValues();
		computeAverage();
		generateArrayOfTraits();
		return new Phenotype(averageTraits);

	}

	private void computeSumOfTraitValues() {
		for (Phenotype phenotype : collection) {
			traitValues = phenotype.getArrayOfVariables();
			addTraitValuesToSum();
		}
	}

	private void generateArrayOfTraits() {
		averageTraits = new Trait[numberOfTraits];
		for (int i = 0; i < numberOfTraits; i++) {
			averageTraits[i] = new Trait(averageTraitValues[i]);
		}
	}

	private void computeAverage() {
		for (int i = 0; i < numberOfTraits; i++) {
			averageTraitValues[i] = sumOfTraitValues[i] / collection.size();
		}
	}

	private void addTraitValuesToSum() {
		for (int i = 0; i < numberOfTraits; i++) {
			sumOfTraitValues[i] = sumOfTraitValues[i] + traitValues[i];
		}
	}

}
